import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import vueDevTools from 'vite-plugin-vue-devtools'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { NaiveUiResolver } from 'unplugin-vue-components/resolvers'
import path from 'node:path'
import { readFileSync } from 'node:fs'

function getExports(filePath: string) {
  const content = readFileSync(path.resolve(__dirname, filePath), 'utf-8')
  return (
    content.match(/export (const|enum|function) (\w+)/g)?.map((match) => match.split(' ')[2]) || []
  )
}

// https://vitejs.dev/config/
export default defineConfig({
  server: {
    port: 8080
  },
  plugins: [
    vue({}),
    vueJsx(),
    vueDevTools(),
    AutoImport({
      imports: [
        'vue',
        'vue-router',
        'pinia',
        {
          '@/stores/modules/code': ['useCodeStore'],
          '@/stores/modules/user': ['useUserStore'],
          '@/stores/modules/role': ['useRoleStore'],
          '@/stores/modules/menu': ['useMenuStore'],
          '@/stores/modules/app': ['useAppStore'],
          '@/stores/modules/tag': ['useTagStore'],
          '@/enums': getExports('./src/enums/index.ts'),
          '@/utils/cache': getExports('./src/utils/cache.ts'),
          '@/utils/common': getExports('./src/utils/common.ts'),
          '@/utils/global': getExports('./src/utils/global.ts'),
          '@/utils/message': getExports('./src/utils/message.ts'),
          '@/utils/utils': getExports('./src/utils/utils.ts'),
          '@/utils/methods': getExports('./src/utils/methods.ts')
        },
        {
          from: 'naive-ui',
          imports: ['FormRules', 'DataTableColumns', 'SelectOption'],
          type: true
        }
      ],
      dirs: [],
      vueTemplate: true,
      eslintrc: {
        //这里先设置为true，npm run dev运行后生成.eslintrc-auto-import.json文件之后，再改为false
        enabled: false,
        // filepath: './.eslintrc-auto-import.json'
        filepath: './.eslintrc-auto-import.json'
      }
    }),
    Components({
      resolvers: [NaiveUiResolver()]
    })
  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  }
})
